"""
  Author:     Adrian Mandy <jatmandy@gmail.com>
  Program:    Litigation Manager.
  Date:       January 15, 2008

  Description:  GUI for manipulating litigation support files
                
                todo:

"""

import sys, os, re
import litlib2
from PyQt4 import QtCore, QtGui, QtSql, uic

class documentListMdi(QtGui.QTableView):
    sequenceNumber = 1
    def __init__(self, db, table):
        QtGui.QTableView.__init__(self, None)

        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.isUntitled = True
        self.whereClause = ""
        self.keyField = "Imgtag"
        self.imageField = "Imgfiles"
        self.pathField = "Defdir"
        self.tableName = table
        self.dbtable = litlib2.Case(db, table)
        self.setSortingEnabled(False)
        self.horizontalHeader().setMovable(True)

    def newFile(self):
        self.isUntitled = True
        documentListMdi.sequenceNumber += 1
        self.setWindowTitle(self.tableName)
        
        self.model = self.dbtable.table()
        self.setModel(self.model)
        
    def importFile(self, filename, delims=['\|', '\^', ';', '~'], fregex="(${q}(?:[^${q}]|${q}${q})*${q}|[^,$$]*)(?:${f}|$$)?"):
        self.isUntitled = True
        documentListMdi.sequenceNumber += 1
        self.setWindowTitle(self.query)
        self.dbtable.Read(filename, delims, fregex)

        self.model = self.dbtable.table()
        self.setModel(self.model)
        
    def importTagFile(self, filename):
        self.isUntitled = True
        documentListMdi.sequenceNumber += 1
        self.setWindowTitle(self.tableName+" "+str(self.sequenceNumber))
        self.dbtable.readTagFile(filename)

        self.model = self.dbtable.table()
        self.setModel(self.model)
        
    def importIdsFile(self, filename):
        self.isUntitled = True
        documentListMdi.sequenceNumber += 1
        self.setWindowTitle(self.tableName+" "+str(self.sequenceNumber))
        self.dbtable.idsRead(filename)

        self.model = self.dbtable.table()
        self.setModel(self.model)

    def importConcFile(self, filename, delims=['\|', '\^', ';', '~'], fregex="(${q}(?:[^${q}]|${q}${q})*${q}|[^,$$]*)(?:${f}|$$)?"):
        self.isUntitled = True
        documentListMdi.sequenceNumber += 1
        self.setWindowTitle(self.tableName+" "+str(self.sequenceNumber))
        self.dbtable.concRead(filename, delims, fregex)

        self.model = self.dbtable.table()
        self.setModel(self.model)

    def filter(self, whereFilter):
        self.whereClause = whereFilter
        if whereFilter.isEmpty():
            self.model.setFilter("")
        else:
            self.model.setFilter(self.whereClause)
            self.model.select()

    def purge(self):
        self.dbtable.purge()
        self.model.select()
        
    def currentColumn(self):
        return self.column()
        
    def export(self, filename):
        self.dbtable.out(self.model, filename)
        
    def exportImages(self, filename):
        self.dbtable.imagesOut(filename)
        
    def exportTags(self, filename):
        self.dbtable.tagOut(filename)
        
    def exportCopyList(self, filename):
        self.dbtable.List(filename)

    def walkDir(self, imageDir, dir, pathkey):
        self.dbtable.dirWalk(imageDir, dir, pathkey = pathkey)

class queryDocumentListMdi(documentListMdi):
    def __init__(self, db, table, query):
        QtGui.QTableView.__init__(self, None)
        
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.isUntitled = True
        self.whereClause = ""
        self.keyField = "Imgtag"
        self.imageField = "Imgfiles"
        self.pathField = "Defdir"
        self.query = query
        self.tableName = table
        self.dbtable = litlib2.Case(db, table)
        self.setSortingEnabled(False)
        self.horizontalHeader().setMovable(True)

    def filter(self, whereFilter):
        self.whereClause = whereFilter
        filter = self.query + " WHERE " + self.whereClause
        self.setWindowTitle(filter)
        if whereFilter.isEmpty():
            self.model.setQuery(self.query)
        else:
            self.model.setQuery(filter)
        self.setModel(self.model)

    def newFile(self):
        self.isUntitled = True
        documentListMdi.sequenceNumber += 1
        self.setWindowTitle(self.query)
        self.model = QtSql.QSqlQueryModel()
        self.model.setQuery(self.query)
        self.setModel(self.model)

sandr_class, base_class = uic.loadUiType("searchAndReplace.ui")
class searchAndReplace(base_class, sandr_class):
    def __init__(self):
        base_class.__init__(self, None)
        self.setupUi(self)

tables_class, base_class = uic.loadUiType("PickTable.ui")
class pickTable(QtGui.QDialog, tables_class):
    def __init__(self, db, tableName):
        QtGui.QDialog.__init__(self, None)
        self.setupUi(self)
        self.model = QtSql.QSqlQueryModel()
        self.model.setQuery("select name from sqlite_master")
        self.comboBox.setModel(self.model)
        if len(tableName) > 0:
            self.comboBox.setEditable(True)
            self.comboBox.setEditText(tableName)

tables_class, base_class = uic.loadUiType("jointables.ui")
class pickTables(base_class, tables_class):
    def __init__(self):
        base_class.__init__(self, None)
        self.setupUi(self)
        self.model = QtSql.QSqlQueryModel()
        self.model.setQuery("select name from sqlite_master")
        self.table1.setModel(self.model)
        self.table2.setModel(self.model)

tables_class, base_class = uic.loadUiType("dirWalk.ui")
class uiDirectoryWalk(QtGui.QDialog, tables_class):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.setupUi(self)

tables_class, base_class = uic.loadUiType("imageView.ui")
class imageViewWindow(base_class, tables_class):
    sequenceNumber = 0
    def __init__(self, pageList = ['image1.tif', 'image2.tif', 'image3.tif', 'image4.tif', 'image5.tif'], currentPage = 0):
        base_class.__init__(self, None)
        self.setupUi(self)
        self.scaleFactor = 1.0
        imageViewWindow.sequenceNumber += 1
        self.pageList = pageList
        self.currentPage = currentPage

        self.documentImagePixmap = QtGui.QPixmap()
        self.documentImageScene = QtGui.QGraphicsScene()
        self.documentImageView = QtGui.QGraphicsView(self.documentImageScene)

        self.documentImageView.setBackgroundRole(QtGui.QPalette.Dark)
        self.documentImageView.setObjectName("scrollarea")
        self.documentImageView.setDragMode(QtGui.QGraphicsView.ScrollHandDrag)
        self.gridlayout.addWidget(self.documentImageView, 0, 0, 1, 1)
        self.updatePage()

    def setPageList(self, pageList):
        self.pageList = pageList
        print(self.pageList)
        self.currentPage = 0
        self.updatePage()

    def nextPage(self):
        self.currentPage += 1
        if self.currentPage == len(self.pageList):
            self.currentPage -=1
        else:
            self.updatePage()

    def prevPage(self):
        self.currentPage -= 1
        if self.currentPage < 0:
            self.currentPage +=1
        else:
            self.updatePage()

    def firstPage(self):
        self.currentPage = 0
        self.updatePage()

    def lastPage(self):
        self.currentPage = len(self.pageList)-1
        self.updatePage()

    def updatePage(self):
        #im = Image.open(self.pageList[self.currentPage])
        #qim = QtGui.QImage()
        self.documentImagePixmap.load(self.pageList[self.currentPage])
        #print qim.load(self.pageList[self.currentPage])
        #self.imageLabel.setPixmap(self.pix.fromImage(qim))
        #self.pix.fromImage(ImageQt.ImageQt(im))
        self.documentImageScene.addPixmap(self.documentImagePixmap) #setPixmap
        self.setWindowTitle(self.pageList[self.currentPage] +" ("+ str(self.currentPage+1) +"/"+ str(len(self.pageList))+")")

    def scaleImage(self, factor):
        #self.scaleFactor *= factor
        #self.imageLabel.resize(factor * self.imageLabel.size())
        self.documentImageView.scale(factor, factor)
        self.adjustScrollBar(self.documentImageView.horizontalScrollBar(), factor)
        self.adjustScrollBar(self.documentImageView.verticalScrollBar(), factor)

        #zoomInAct.setEnabled(scaleFactor < 3.0);
        #zoomOutAct.setEnabled(scaleFactor > 0.333);

    def adjustScrollBar(self, scrollBar, factor):
        scrollBar.setValue(int(factor * scrollBar.value() + ((factor - 1) * scrollBar.pageStep()/2)))

view_class, base_class = uic.loadUiType("treeView.ui")
class treeViewWindow(base_class, view_class):
    def __init__(self):
        base_class.__init__(self, None)
        self.setupUi(self)

view_class, base_class = uic.loadUiType("fullTextView.ui")
class fullTextViewWindow(base_class, view_class):
    def __init__(self):
        base_class.__init__(self, None)
        self.setupUi(self)

class preferenceStore:
    def __init__(self, db, preferenceTable="litman_pref"):
        """If preference table does not exist create it with defaults
        """
        if not db.has_table(preferenceTable):
            db.create_table(preferenceTable, ["key","value"])
            db.Prepare(preferenceTable, ["key", "value"])
            db.Add([("key","delim_import_field"),("value",",")])
            db.Add([("key","delim_import_quote"),("value",'"')])
            db.Add([("key","delim_import_multi"),("value",";")])
            db.Add([("key","delim_import_cr"),("value","~")])
            db.Add([("key","regex_filename_key"),("value","(([a-zA-Z]+-[0-9]{2})[0-9]+.*)")])
            db.Add([("key","regex_field_data"),("value","(${q}(?:[^${q}]|${q}${q})*${q}|(?:^)[^${f}]*(?=$$)|(?<=${f})[^${f}]*(?=$$)|[^${f}]*(?=${f}))(?:${f}|$$)?")])
            db.Add([("key","regex_field_names"),("value","(?:^|${f})${q}?(.*?)${q}?(?=${f}|$$)")])
        self.pref = db.getTable(preferenceTable)
        #("(?:[^"]|"")*"|(?<=,)[^,]*(?=$)|[^,]*(?=,))(?:,|$)?    This one seems best for now
        #,(?=([^"]*"[^"]*")*(?![^"]*"))
        #(?:^|,)("(?:[^"]|"")*"|[^,]*)
        #\G(,|\r?\n|\r|^)(?:"([^"]*+(?>""[^"]*+)*)"|([^",\r\n]*+))  This one has features not supported in python regex but is probably more efficient
        
    def getKey(self, key):
        self.pref.setFilter("key = '"+key+"'")
        self.pref.select()
        return self.pref.record(0).value("value")
        
    def getDelimiters(self):
        field = str(self.getKey("delim_import_field"))
        quote = str(self.getKey("delim_import_quote"))
        cr = str(self.getKey("delim_import_cr"))
        multi = str(self.getKey("delim_import_multi"))
        return [field, quote, multi, cr]

form_class, base_class = uic.loadUiType("Main.ui")
class litmanMainWindow(base_class, form_class):
    def __init__(self, parent=None):
        base_class.__init__(self, parent)
        self.setupUi(self)
        
        self.workspace = QtGui.QWorkspace()
        self.filename = ""
        self.setCentralWidget(self.workspace)
        self.statusBar().showMessage(self.tr("Ready"))
        self.db = litlib2.dbSql(dbFile="litman.db")
        self.preferences = preferenceStore(self.db)

    def createMdiChild(self, table):
        child = documentListMdi(self.db, table)
        self.workspace.addWindow(child)
        return child

    def createQueryChild(self, table, query):
        child = queryDocumentListMdi(self.db, table, query)
        self.workspace.addWindow(child)
        child.newFile()
        self.connect(child.verticalHeader(), QtCore.SIGNAL("sectionClicked(int)"), self.display)
        child.show()
        return child

    def createImageChild(self):
        child = imageViewWindow()
        self.workspace.addWindow(child)
        return child

    def activeMdiChild(self):
        return self.workspace.activeWindow()

    def selectedColumns(self):
        return [self.activeMdiChild().horizontalHeader().model().headerData(column.column(), QtCore.Qt.Horizontal) for column in self.activeMdiChild().selectionModel().selectedColumns()]

    #File Menu
    @QtCore.pyqtSignature("")
    def on_action_New_triggered(self):
        pickedTable = pickTable(self.db, "")
        if pickedTable.exec_() == QtGui.QDialog.Accepted:
            table = pickedTable.comboBox.currentText()
            query = "SELECT * FROM " + table
            child = self.createQueryChild(table, query)
            child.newFile()
            self.connect(child.verticalHeader(), QtCore.SIGNAL("sectionClicked(int)"), self.display)
            child.show()

    @QtCore.pyqtSignature("")
    def on_action_Open_triggered(self):
        self.filename = QtGui.QFileDialog.getSaveFileName(self, 
                                         self.tr("QFileDialog.getOpenFileName()"), 
                                         self.filename, 
                                         self.tr("All Files (*.db);;Text Files (*)"))
        self.db = litlib2.dbSql(dbFile=self.filename)
        self.preferences = preferenceStore(self.db)

    def display(self, n):
        imageFiles = str(self.activeMdiChild().model.data(self.activeMdiChild().model.index(n, 2, QtCore.QModelIndex())))
        imageDefDir =str(self.activeMdiChild().model.data(self.activeMdiChild().model.index(n, 1, QtCore.QModelIndex())))
        images = litlib2.ImageNames(imageFiles, imageDefDir)
        print(imageFiles)
        print(images.FileNames())
        print(imageDefDir)
        print(images.FullFileNames('sampleData'))
        self.imageWin.setPageList(images.FullFileNames('sampleData'))

    @QtCore.pyqtSignature("")
    def on_actionI_mport_Summaries_triggered(self):
        self.filename = QtGui.QFileDialog.getOpenFileName(self, 
                                         self.tr("QFileDialog.getOpenFileName()"), 
                                         self.filename, 
                                         self.tr("All Files (*);;Text Files (*.txt)"))
        if len(self.filename)>0:
            self.statusBar().showMessage(self.tr("Loading..."))
            tableName = os.path.splitext(os.path.basename(str(self.filename)))[0]
            pickedTable = pickTable(self.db, tableName)
            if pickedTable.exec_() == QtGui.QDialog.Accepted:
                tableName = pickedTable.comboBox.currentText()
                #child = self.createMdiChild(tableName)
                query = "SELECT * FROM " + tableName
                child = self.createQueryChild(tableName, query)
                child.tableName = tableName
                child.importFile(self.filename, self.preferences.getDelimiters(), str(self.preferences.getKey("regex_field_data")))
                self.connect(child.verticalHeader(), QtCore.SIGNAL("sectionClicked(int)"), self.display)
                child.show()
            self.statusBar().showMessage(self.tr("Ready"))

    @QtCore.pyqtSignature("")
    def on_actionTable_triggered(self):
        activeModel = self.activeMdiChild().model
        while activeModel.canFetchMore():
            activeModel.fetchMore()

        columnCount = activeModel.columnCount()
        columns = [str(activeModel.headerData(cindex, QtCore.Qt.Horizontal).toString()) for cindex in range(columnCount)]
        print(columns)
        rowe = activeModel.rowCount()
        for row in range(0, rowe):
            print([str(activeModel.data(activeModel.createIndex(row, column)).toString()) for column in range(columnCount)])

#        print self.preferences.getDelimiters()
    
#        while self.activeMdiChild().model.canFetchMore():
#            self.activeMdiChild().model.fetchMore()
#        
#        rowe = self.activeMdiChild().model.rowCount()
#        print rowe
#        for i in range(0, rowe):
#            record = self.activeMdiChild().model.record(i)
#        print "Totals rows:",rowe

##        if imageViewWindow.sequenceNumber < 1:
##            child = self.createImageChild()
##            #child.scaleImage(0.3)
##            child.show()
##            self.imageWin = child

##        sel = self.activeMdiChild().selectionModel()
##        indexes = self.activeMdiChild().selectedIndexes()
##        print indexes
##        for index in indexes:
##            print "Index:", self.activeMdiChild().horizontalHeader().model().headerData(index.column(),  QtCore.Qt.Horizontal).toString()
##            print "Data:", self.activeMdiChild().model.data(self.activeMdiChild().model.index(0,1, QtCore.QModelIndex())).toString()
##        for column in self.activeMdiChild().selectionModel().selectedColumns():
##            print "COL:",  column.column()
##            print self.activeMdiChild().horizontalHeader().model().headerData(column.column(),  QtCore.Qt.Horizontal).toString()
##        print self.activeMdiChild().horizontalHeader().model().headerData(column.column(),  QtCore.Qt.Horizontal).toString()
##        table = pickTable(self.db)
##        if table.exec_() == QtGui.QDialog.Accepted:
##            print "Pick:", table.comboBox.currentText()


    #Edit Menu
    @QtCore.pyqtSignature("")
    def on_action_Add_Record_triggered(self):
        self.activeMdiChild().model.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange)
        self.activeMdiChild().model.insertRows(0, 1)

    def on_action_Replace_triggered(self):
        search = searchAndReplace()
        if search.exec_() == QtGui.QDialog.Accepted:
            searchFor = str(search.searchFor.text())
            print(searchFor)
            replaceWith = str(search.replaceWith.text())
            print(replaceWith)
            finder = re.compile(searchFor)
            
            while self.activeMdiChild().model.canFetchMore():
                self.activeMdiChild().model.fetchMore()

            column = self.activeMdiChild().selectionModel().selectedColumns()[0].column()
            print(column)
            rowe = self.activeMdiChild().model.rowCount()
            activeModel = self.activeMdiChild().model
            replaceCount = 0
            recordsAffected = 0
            for row in range(0, rowe):
                index = activeModel.createIndex(row, column)
                oldString = str(activeModel.data(index).toString())
                replaceResult = finder.subn(replaceWith, oldString)
                replaceCount += replaceResult[1]
                if replaceResult[1] > 0:
                    recordsAffected += 1
                    print(replaceResult[0])
                    activeModel.setData(index, QtCore.QVariant(replaceResult[0]))
            self.activeMdiChild().model.submitAll()
            print(replaceCount, "replacements made, ", recordsAffected, "records affected.")


    @QtCore.pyqtSignature("")
    def on_actionPrefi_x_triggered(self):
        text, ok = QtGui.QInputDialog.getText(self, self.tr("QInputDialog.getText()"), 
                                              self.tr("Prefix:"), QtGui.QLineEdit.Normal, 
                                              self.activeMdiChild().whereClause)
        if ok:
            if len(self.selectedColumns()) > 0:
                column = self.selectedColumns()[0]
                tableName = self.activeMdiChild().tableName
                self.db.prefix(tableName, column, text)
                self.activeMdiChild().model.select()

    @QtCore.pyqtSignature("")
    def on_action_Filter_triggered(self):
        text, ok = QtGui.QInputDialog.getText(self, self.tr("QInputDialog.getText()"), 
                                              self.tr("WHERE:"), QtGui.QLineEdit.Normal, 
                                              self.activeMdiChild().whereClause)
        if ok:
            self.activeMdiChild().filter(text)

    @QtCore.pyqtSignature("")
    def on_actionPur_ge_triggered(self):
        self.activeMdiChild().purge()

    @QtCore.pyqtSignature("")
    def on_action_Drop_Table_triggered(self):
        pickedTable = pickTable(self.db, "")
        if pickedTable.exec_() == QtGui.QDialog.Accepted:
            tableName = pickedTable.comboBox.currentText()
            self.db.drop(tableName)

    @QtCore.pyqtSignature("")
    def on_actionPreferences_triggered(self):
        child = self.createMdiChild("litman_pref")
        child.newFile()
        child.show()

    #View Menu
    @QtCore.pyqtSignature("")
    def on_actionTree_Viewer_triggered(self):
        self.treeView = treeViewWindow()
        self.workspace.addWindow(self.treeView)
        dock = QtGui.QDockWidget(self.tr(str("Tree View")), self)
        dock.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea)
        dock.setWidget(self.treeView)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)

    @QtCore.pyqtSignature("")
    def on_actionImage_Viewer_triggered(self):
        if imageViewWindow.sequenceNumber < 1:
        
            self.imageWin = self.createImageChild()
            #child.scaleImage(0.3)
            dock = QtGui.QDockWidget(self.tr(str("Image Viewer")), self)
            dock.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea)
            dock.setWidget(self.imageWin)
            self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)

            #child.show()

    @QtCore.pyqtSignature("")
    def on_action_Next_Page_triggered(self):
        self.imageWin.nextPage()

    @QtCore.pyqtSignature("")
    def on_action_Previous_Page_triggered(self):
        self.imageWin.prevPage()

    @QtCore.pyqtSignature("")
    def on_action_First_Page_triggered(self):
        self.imageWin.firstPage()

    @QtCore.pyqtSignature("")
    def on_action_Last_Page_triggered(self):
        self.imageWin.lastPage()

    @QtCore.pyqtSignature("")
    def on_actionZoom_In_triggered(self):
        self.imageWin.scaleImage(1.25)

    @QtCore.pyqtSignature("")
    def on_actionZoom_Out_triggered(self):
        self.imageWin.scaleImage(0.75)

    @QtCore.pyqtSignature("")
    def on_actionZoom_100_triggered(self):
        self.imageWin.scaleImage(1)

    #Tools Menu
    @QtCore.pyqtSignature("")
    def on_action_Walk_Image_Directory_triggered(self):
        walk = uiDirectoryWalk()
        if walk.exec_() == QtGui.QDialog.Accepted:
            child = self.createMdiChild(walk.dirPath.text())
            child.walkDir(str(walk.walkPath.text()), str(walk.dirPath.text()), pathkey = walk.pathKey.checkState())
            child.show()

    @QtCore.pyqtSignature("")
    def on_actionImport_Tag_File_triggered(self):
        self.filename = QtGui.QFileDialog.getOpenFileName(self, 
                                         self.tr("QFileDialog.getOpenFileName()"), 
                                         self.filename, 
                                         self.tr("All Files (*);;Text Files (*.txt);;Dii Files (*.dii)"))
        if not self.filename.isEmpty():
            self.statusBar().showMessage(self.tr("Loading..."))
            tableName = os.path.splitext(os.path.basename(str(self.filename)))[0]
            pickedTable = pickTable(self.db, tableName)
            if pickedTable.exec_() == QtGui.QDialog.Accepted:
                tableName = pickedTable.comboBox.currentText()
                print(tableName)
                child = self.createMdiChild(tableName)
                child.importTagFile(self.filename)
                #self.connect(child.verticalHeader(), QtCore.SIGNAL("sectionClicked(int)"), self.display)
                child.show()
            self.statusBar().showMessage(self.tr("Ready"))
            
    #actionImport_Conc_List
    @QtCore.pyqtSignature("")
    def on_actionImport_Conc_List_triggered(self):
        self.filename = QtGui.QFileDialog.getOpenFileName(self, 
                                         self.tr("QFileDialog.getOpenFileName()"), 
                                         self.filename, 
                                         self.tr("All Files (*);;Opt Files (*.opt);;Text Files (*.txt)"))
        if not self.filename.isEmpty():
            self.statusBar().showMessage(self.tr("Loading..."))
            tableName = os.path.splitext(os.path.basename(str(self.filename)))[0]
            pickedTable = pickTable(self.db, tableName)
            if pickedTable.exec_() == QtGui.QDialog.Accepted:
                tableName = pickedTable.comboBox.currentText()
                print(tableName)
                child = self.createMdiChild(tableName)
                child.importConcFile(self.filename, self.preferences.getDelimiters(), str(self.preferences.getKey("regex_field_data")))
                #self.connect(child.verticalHeader(), QtCore.SIGNAL("sectionClicked(int)"), self.display)
                child.show()
            self.statusBar().showMessage(self.tr("Ready"))

    @QtCore.pyqtSignature("")
    def on_actionImport_Ids_File_triggered(self):
        self.filename = QtGui.QFileDialog.getOpenFileName(self, 
                                         self.tr("QFileDialog.getOpenFileName()"), 
                                         self.filename, 
                                         self.tr("All Files (*);;Text Files (*.txt);;Dii Files (*.dii)"))
        if not self.filename.isEmpty():
            self.statusBar().showMessage(self.tr("Loading..."))
            tableName = os.path.splitext(os.path.basename(str(self.filename)))[0]
            pickedTable = pickTable(self.db, tableName)
            if pickedTable.exec_() == QtGui.QDialog.Accepted:
                tableName = pickedTable.comboBox.currentText()
                print(tableName)
                child = self.createMdiChild(tableName)
                child.importIdsFile(self.filename)
                #self.connect(child.verticalHeader(), QtCore.SIGNAL("sectionClicked(int)"), self.display)
                child.show()
            self.statusBar().showMessage(self.tr("Ready"))

    @QtCore.pyqtSignature("")
    def on_actionExport_Summaries_triggered(self):
        filename = QtGui.QFileDialog.getSaveFileName(self, 
                                         self.tr("QFileDialog.getSaveFileName()"), 
                                         self.filename, 
                                         self.tr("All Files (*);;Text Files (*.txt)"))
        if not filename.isEmpty():
            print(self.filename)
            self.activeMdiChild().export(open(filename, 'w'))

    @QtCore.pyqtSignature("")
    def on_actionExport_Images_triggered(self):
        filename = QtGui.QFileDialog.getSaveFileName(self, 
                                         self.tr("QFileDialog.getSaveFileName()"), 
                                         self.filename, 
                                         self.tr("All Files (*);;Text Files (*.txt)"))
        if not filename.isEmpty():
            print(self.filename)
            self.activeMdiChild().exportImages(open(filename, 'w'))

    @QtCore.pyqtSignature("")
    def on_actionExport_Tags_triggered(self):
        filename = QtGui.QFileDialog.getSaveFileName(self, 
                                         self.tr("QFileDialog.getSaveFileName()"), 
                                         self.filename, 
                                         self.tr("All Files (*);;Text Files (*.txt)"))
        if not filename.isEmpty():
            print(self.filename)
            self.activeMdiChild().exportTags(open(filename, 'w'))

    @QtCore.pyqtSignature("")
    def on_actionExport_Copy_List_triggered(self):
        filename = QtGui.QFileDialog.getSaveFileName(self, 
                                         self.tr("QFileDialog.getSaveFileName()"), 
                                         self.filename, 
                                         self.tr("All Files (*);;Text Files (*.txt)"))
        if not filename.isEmpty():
            print(self.filename)
            self.activeMdiChild().exportCopyList(open(filename, 'w'))

    @QtCore.pyqtSignature("")
    def on_action_Join_triggered(self):
        pickedTables = pickTables()
        if pickedTables.exec_() == QtGui.QDialog.Accepted:
            table1 = pickedTables.table1.currentText()
            table2 = pickedTables.table2.currentText()
            key1 = pickedTables.keyfield1.currentText()
            key2 = pickedTables.keyfield2.currentText()
            query = "SELECT "+table1+".* FROM "+table1+" INNER JOIN "+table2+" ON "+table1+"."+key1+"="+table2+"."+key2
            child = self.createQueryChild(table1, query)

    @QtCore.pyqtSignature("")
    def on_actionDuplicates_triggered(self):
        if len(self.selectedColumns()) > 0:
            column = self.selectedColumns()[0]
            #tableName = self.activeMdiChild().tableName
            xquery = self.activeMdiChild().query
            query = "SELECT "+column+", COUNT("+column+") AS Tally FROM ("+xquery+") GROUP BY "+column+" HAVING (COUNT("+column+") > 0) ORDER BY COUNT("+column+") DESC"
            child = self.createQueryChild(xquery, query)

    #Help Menu
    @QtCore.pyqtSignature("")
    def on_action_About_triggered(self):
        QtGui.QMessageBox.about(self, "About Litigation Manager", 
                    "Litman\n\n"
                    "Litigation Manager\n"
                    "Copyright (C) 2008 Adrian Mandy\n"
                    "A MandySoft production.")


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    app.addLibraryPath("plugins")
    
    ui = litmanMainWindow()
    ui.show()
    sys.exit(app.exec_())
